import socket
import sys
import threading


class Server(threading.Thread):
    ip = socket.gethostbyname(socket.gethostname())
    print(ip)
    port = 9999
    def __init__(self):
        threading.Thread.__init__(self)
        #创建socket对象
        self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    def load(self):
        self.s.bind((self.ip, self.port))
        self.s.listen(5)
        self.clientsocket, self.addr = self.s.accept()
        print("{0}发起了连接".format(str(self.addr)))
    def receiveClietMessage(self):
        try:
            clientmsg = self.clientsocket.recv(1024)
        except:
            print("The client exits.")
            self.clientsocket.close()
            self.clientsocket, self.addr = self.s.accept()
            print("{0}发起了连接".format(str(self.addr)))
        else:
            print("[client] >>> {0}".format(clientmsg.decode("utf-8")))

    def sendClientMesage(self,msg):
        try:
            self.clientsocket.send(msg.encode("utf-8"))
            # clientsocket.close()
        except:
            print("The client exits.")
            self.clientsocket.close()
            raise Exception("The server exits.")

    def run(self) -> None:
        self.load()
        while True:
            self.receiveClietMessage()

server = Server()
server.start()
while True:
    # t2 = threading.Thread(target=server.sendClientMesage())
    # t2.start()

    print(">>> ")
    msg = input()
    server.sendClientMesage(msg)
